package com.docmgmt.mvp.controller;

import com.docmgmt.mvp.dto.FileVersionVO;
import com.docmgmt.mvp.dto.RestoreVersionRequest;
import com.docmgmt.mvp.dto.Result;
import com.docmgmt.mvp.exception.UnauthorizedException;
import com.docmgmt.mvp.service.FileVersionService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 文件版本管理控制器
 *
 * @author Dora
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/files")
@RequiredArgsConstructor
public class FileVersionController {

    private final FileVersionService fileVersionService;

    /**
     * 4.4.1 查看文件版本历史
     *
     * GET /api/v1/files/{id}/versions
     */
    @GetMapping("/{fileId}/versions")
    public Result<List<FileVersionVO>> listFileVersions(@PathVariable Long fileId) {
        Long userId = getCurrentUserId();

        log.info("GET /api/v1/files/{}/versions - userId={}", fileId, userId);

        List<FileVersionVO> versions = fileVersionService.listFileVersions(fileId, userId);
        return Result.success("查询成功", versions);
    }

    /**
     * 4.4.2 恢复到指定版本
     *
     * POST /api/v1/files/{id}/versions/restore
     */
    @PostMapping("/{fileId}/versions/restore")
    public Result<FileVersionVO> restoreVersion(
            @PathVariable Long fileId,
            @Valid @RequestBody RestoreVersionRequest request) {
        Long userId = getCurrentUserId();

        log.info("POST /api/v1/files/{}/versions/restore - userId={}, version={}",
                fileId, userId, request.getVersion());

        FileVersionVO version = fileVersionService.restoreVersion(
                fileId, request.getVersion(), userId, request.getComment());
        return Result.success("版本恢复成功", version);
    }

    /**
     * 从Spring Security上下文获取当前用户ID
     */
    private Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            throw new UnauthorizedException("未登录或认证已过期");
        }

        Object principal = authentication.getPrincipal();
        if (principal instanceof Long) {
            return (Long) principal;
        }

        throw new UnauthorizedException("无效的认证信息");
    }
}
